package com.wswy.wzcx.ui.car.result;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.utils.CollectionUtils;
import com.che.libcommon.utils.RxBus;
import com.che.libcommon.utils.RxHelper;
import com.che.libcommon.utils.ToastUtils;
import com.che.libcommon.utils.optional.Optional;
import com.wswy.wzcx.model.AdModel;
import com.wswy.wzcx.model.CarInfoModel;
import com.wswy.wzcx.model.Converter;
import com.wswy.wzcx.model.JZCFMode;
import com.wswy.wzcx.model.TrafficViolationInfo;
import com.wswy.wzcx.model.car.CarExtendInfo;
import com.wswy.wzcx.model.car.CarTypeData;
import com.wswy.wzcx.model.car.CarTypeInfo;
import com.wswy.wzcx.model.license.UserCarInfo;
import com.wswy.wzcx.model.resp.QueryResult;
import com.wswy.wzcx.model.resp.TrafficViolationResp;
import com.wswy.wzcx.module.GlobalConfigManager;
import com.wswy.wzcx.module.InternalMsgCode;
import com.wswy.wzcx.module.UserDataProvider;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.ResourceObserver;
import io.reactivex.subscribers.ResourceSubscriber;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import timber.log.Timber;

class QueryResultPresenter {

    private static final String TAG = "QueryResultPresenter";

    private CompositeDisposable disposables = new CompositeDisposable();

    private Context context;
    private IQueryResultView queryResultView;

    private UserCarInfo userCarInfo;

    private AdModel adModel;
    private boolean loadedResult = false;

    private Map<String, TrafficViolationInfo> lastFines = new HashMap<>();

    private boolean inLoading = false;

    private boolean skipComp = true;

    QueryResultPresenter(Context context,
                         IQueryResultView queryResultView) {
        this.context = context;
        this.queryResultView = queryResultView;
    }

    void onCreate(Intent intent) {
        userCarInfo = intent.getParcelableExtra("carInfo");
        int carId = -1;
        if (userCarInfo != null) {
            carId = userCarInfo.id;
        }

        QueryResult result = intent.getParcelableExtra("query.result");
        if (result == null) {
            queryFine(carId);
        } else {
            loadedResult = true;
            showWithResult(result);
        }


        ResourceObserver<UserCarInfo> observer = new ResourceObserver<UserCarInfo>() {
            @Override
            public void onNext(UserCarInfo userCarInfo) {
                queryResultView.updateExtendInfo(userCarInfo);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

        ResourceObserver<JZCFMode> observerJZAdd = new ResourceObserver<JZCFMode>() {
            @Override
            public void onNext(JZCFMode jzcfMode) {
                //添加驾照
                addJZ(jzcfMode);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

        ResourceObserver<JZCFMode> observerJZDelete = new ResourceObserver<JZCFMode>() {
            @Override
            public void onNext(JZCFMode jzcfMode) {
                deleteJZ(jzcfMode);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

        disposables.add(observer);
        disposables.add(observerJZAdd);
        disposables.add(observerJZDelete);

        RxBus.getDefault()
                .toObservableWithCode(InternalMsgCode.CODE_UPDATE_EXTEND, UserCarInfo.class)
                .subscribe(observer);

        RxBus.getDefault()
                .toObservableWithCode(InternalMsgCode.CODE_ADD_JZ, JZCFMode.class)
                .subscribe(observerJZAdd);

        RxBus.getDefault()
                .toObservableWithCode(InternalMsgCode.CODE_DELETE_JZ, JZCFMode.class)
                .subscribe(observerJZDelete);

        loadAD();
    }

    void reload() {
        if (userCarInfo != null && !inLoading) {
            queryFine(userCarInfo.id, true, true);
        }
    }

    private void loadAD() {
        AdModel wzcxAd = GlobalConfigManager.getInstance().getAdsConf().getWzcxAd();
        if (wzcxAd != null) {
            adModel = wzcxAd;
            if (loadedResult) {
                queryResultView.showAD(adModel);
            }
        }

    }

    private void addJZ(JZCFMode jzcfMode) {
        if (userCarInfo != null && (userCarInfo.driverLicense == null || TextUtils.isEmpty(userCarInfo.driverLicense.getScore()))) {
            //初次添加驾驶证，刷新
            queryFine(userCarInfo.id, true, false);
        }
    }

    private void deleteJZ(JZCFMode jzcfMode) {
        if (userCarInfo != null) {
            queryFine(userCarInfo.id, true, false);
        }
    }

    private void queryFine(int carId) {
        queryFine(carId, false, true);
    }

    private void queryFine(int carId, boolean forceApi, final boolean notify) {
        inLoading = true;
        UserDataProvider.get().carFineList(forceApi, carId)
                .compose(RxHelper.<Optional<TrafficViolationResp>>io2main())
                .subscribe(new QueryResultObserver() {
                    @Override
                    protected void onApiError(@Nullable BaseResult result) {
                        String msg = result.msg;
                        if (TextUtils.isEmpty(msg)) {
                            msg = "系统错误，请稍后重试";
                        }
                        queryResultView.showTips(false, "查询失败，" + msg);
                        queryResultView.showError(userCarInfo, msg);
                        inLoading = false;
                    }

                    @Override
                    protected void onApiResult(@Nullable TrafficViolationResp t) {
                        handleResult(t, notify);

                    }
                });

//    UserDataProvider.get().carFineList(false,carId)
//        //.delay(3, TimeUnit.SECONDS)
//        .compose(RxHelper.<Optional<TrafficViolationResp>>io2main())
//        .subscribe(new ApiOptionalResultObserver<TrafficViolationResp>() {
//
//          @Override
//          protected void onApiError(BaseResult result) {
//            String msg= result.msg;
//            if(TextUtils.isEmpty(msg)){
//              msg = "系统错误，请稍后重试";
//            }
//            queryResultView.showError(null,msg);
//
//          }
//
//          @Override
//          protected void onApiResult(@Nullable TrafficViolationResp resp) {
//
//
//
//          }
//        });
    }

    private void handleResult(TrafficViolationResp resp, boolean notify) {
        if (resp != null) {

            QueryResult queryResult = Converter.INSTANCE.convert2Result(resp);

            userCarInfo = queryResult.userCarInfo;
            queryResultView.showCarInfo(queryResult.userCarInfo, resp.fromCache);

            Timber.e("handleResult --> " + resp.fromCache);

            if (!queryResult.fromCache) {
                inLoading = false;
            }

            if (queryResult.isSuccess()) {

                List<TrafficViolationInfo> fineList = queryResult.fineList;

                //查询成功
                if (CollectionUtils.isEmpty(fineList)) {
                    //没有违章

                    if (!queryResult.noCache) {
                        queryResultView.showEmptySuccess(userCarInfo, queryResult.fromCache);
                    }

                    if (!queryResult.fromCache) {
                        loadedResult = true;
                        if (adModel != null) {
                            queryResultView.showAD(adModel);
                        }
                    }

                    if (!queryResult.noCache && !queryResult.fromCache) {
                        queryResultView.showTips(true, "查询成功，没有违章");
                    }

                } else {
                    //有违章
                    queryResultView.showFines(queryResult.userCarInfo, fineList, queryResult);

                    skipComp = false;

                    if (queryResult.fromCache) {
                        //上次缓存，保存 方便对比

                        for (TrafficViolationInfo trafficViolationInfo : fineList) {

                            if (!TextUtils.isEmpty(trafficViolationInfo.uniqueMd5Id)) {
                                lastFines.put(trafficViolationInfo.uniqueMd5Id, trafficViolationInfo);
                                skipComp = false;
                            } else {
                                skipComp = true;
                            }

//              long id = trafficViolationInfo.id;
//              if (id > 0){
//                lastFines.put(id,trafficViolationInfo);
//                skipComp = false;
//              }else {
//                skipComp = true;
//              }
                        }

                    } else {
                        //网络加载 有违章


                        int newCount = 0;
                        //和缓存比较
                        if (!skipComp) {

                            for (TrafficViolationInfo trafficViolationInfo : fineList) {
                                // 判断上传缓存中的数据条数
                                if (!TextUtils.isEmpty(trafficViolationInfo.uniqueMd5Id) && !lastFines.containsKey(trafficViolationInfo.uniqueMd5Id)) {
                                    newCount++;
                                }
                            }
                        }

                        Log.e(TAG, "handleResult --> newCount:" + newCount);

                        lastFines.clear();
                        for (TrafficViolationInfo trafficViolationInfo : fineList) {
                            //上次结果中没有新的id  保存到缓存
                            if (!TextUtils.isEmpty(trafficViolationInfo.uniqueMd5Id) && !lastFines.containsKey(trafficViolationInfo.uniqueMd5Id)) {
//                long id = trafficViolationInfo.id;
//                if (id > 0){
//                  lastFines.put(id,trafficViolationInfo);
//                }
                                lastFines.put(trafficViolationInfo.uniqueMd5Id, trafficViolationInfo);
                            }
                        }


                        if (notify) {
                            if (newCount == 0) {
                                queryResultView.showTips(true, "查询成功，没有新违章");
                            } else {
                                queryResultView.showTips(true, "查询成功，发现 " + newCount + " 个新违章");
                            }
                        }


                    }

                }
            } else {

                //接口查询失败结果
                if (!queryResult.fromCache) {
                    inLoading = false;

                    if (notify) {
                        queryResultView.showTips(false, "查询失败，请稍后再试");
                    }

                    //查询失败的数据只显示来自接口的查询
                    queryResultView.showError(userCarInfo, queryResult.errorMsg);
                }

            }


        } else {
            inLoading = false;
            queryResultView.showTips(false, "查询失败，请稍后再试");
            queryResultView.showError(userCarInfo, "系统错误，请稍后重试");
        }
    }

    private void showWithResult(QueryResult result) {
        userCarInfo = result.userCarInfo;

        if (userCarInfo != null) {
            queryResultView.showCarInfo(userCarInfo, result.fromCache);
        }

        if (result.errorCode != 0 && !TextUtils.isEmpty(result.errorMsg)) {
            queryResultView.showError(result.userCarInfo, result.errorMsg);
        } else {

            if (CollectionUtils.isEmpty(result.fineList)) {
                queryResultView.showEmptySuccess(userCarInfo, result.fromCache);
            } else {
                queryResultView.showFines(userCarInfo, result.fineList, result);
            }

        }
    }


    UserCarInfo getUserCarInfo() {
        return userCarInfo;
    }


    static void updateCar(UserCarInfo userCarInfo, CarTypeData carTypeData) {

        CarInfoModel carInfoModel = Converter.INSTANCE.userCar2CarModel(userCarInfo);
        CarTypeInfo series = carTypeData.getSeries();
        CarTypeInfo model = carTypeData.getModel();

        if (series != null && model != null) {
            carInfoModel.seriesId = series.getId();
            carInfoModel.specificationId = model.getId();

            if (userCarInfo.carExtendInfo == null) {
                userCarInfo.carExtendInfo = new CarExtendInfo();
            }

            userCarInfo.carExtendInfo.setCarTypeData(carTypeData);


            UserDataProvider.get().updateCarExtendInfo(userCarInfo);

            UserDataProvider.get()
                    .updateCar(userCarInfo.id, carInfoModel.convertQueryMap())
                    .subscribe(new ApiOptionalResultObserver<UserCarInfo>() {

                        @Override
                        protected void onApiResult(@Nullable UserCarInfo userCarInfo) {

                        }

                        @Override
                        protected void onApiError(@Nullable BaseResult result) {
                            ToastUtils.showText("更新车型失败");
                        }
                    });
        }


    }


    void onDestroy() {
        disposables.dispose();
    }


}
